#include "chart.h"

#include <QWebFrame>
#include <QDesktopServices>
#include <QCoreApplication>
#include <QDebug>

Chart::Chart(QWidget *parent)
      : QWebView(parent)
{
    setWindowTitle("Диаграмма пострадавших");

    page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);

    connect(this, SIGNAL(loadFinished(bool)), this, SLOT(setData(bool)));
    connect(this, SIGNAL(linkClicked(QUrl)), this, SLOT(openLinkInBrowser(QUrl)));

}

void Chart::showChart()
{
    load(_url);
    show();
}

void Chart::setData(bool ok)
{
    QString data1_str;
    for (int i = 0; i < data1.count(); ++i) {
        data1_str.append(QString::number(data1.at(i)));
        if (i < data1.count() - 1)
            data1_str.append(",");
    }
    QString data2_str;
    for (int i = 0; i < data2.count(); ++i) {
        data2_str.append(QString::number(data2.at(i)));
        if (i < data2.count() - 1)
            data2_str.append(",");
    }

    qDebug() << QString("showChart([{    name: '%2',     data: [%1]}])")
                          .arg(data1_str, mark1);

    QVariant result = page()->mainFrame()->evaluateJavaScript(QString("data([{"
                                                    "    name: '%2', "
                                                    "    data: [%1]}])")
                                                      .arg(data1_str, mark1) +"; alert('');");
    qDebug() << result.toString();
    
                                                           
    qDebug() << page()->mainFrame()->toHtml();
    qDebug() << page()->mainFrame()->toPlainText();
    this->show();
}

void Chart::clearDiagram(int days)
{
    data1.clear();
    data2.clear();
    for (int i = 0; i < days; ++i) {
        data1.append(0);
        data2.append(0);
    }
}

void Chart::openLinkInBrowser(const QUrl &url)
{
    QDesktopServices::openUrl(url);
}
